package com.atguigu.gulimail.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimail.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimail.product.dao.AttrDao;
import com.atguigu.gulimail.product.dao.AttrGroupDao;
import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.*;
import com.atguigu.gulimail.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimail.product.service.AttrService;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.gulimail.product.vo.AttrEntityRespVO;
import com.atguigu.gulimail.product.vo.AttrEntityVO;
import com.atguigu.gulimail.product.vo.AttrGroupDeleteVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationdao;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String type) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)) {

            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });

        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = page.getRecords();

        List<AttrEntityRespVO> respVOS = list.stream().map((attrEntity) -> {

            AttrEntityRespVO attrEntityRespVO = new AttrEntityRespVO();
            BeanUtils.copyProperties(attrEntity, attrEntityRespVO);

            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity attr_id = attrAttrgroupRelationdao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attr_id != null && attr_id.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                    attrEntityRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());

            if (categoryEntity != null) {
                attrEntityRespVO.setCatelogName(categoryEntity.getName());
            }

            return attrEntityRespVO;

        }).collect(Collectors.toList());


        pageUtils.setList(respVOS);

        return pageUtils;
    }

    @Transactional
    @Override
    public void saveAttrAndGroup(AttrEntityVO attr) {
        //1，保存基本关系
        AttrEntity attrEntity = new AttrEntity();

        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        //2，保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() !=null) {

            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();

            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());

            attrAttrgroupRelationdao.insert(attrAttrgroupRelationEntity);

        }


    }


    @Transactional
    @Override
    public AttrEntityRespVO getAttrInfo(Long attrId) {

        AttrEntityRespVO respVO = new AttrEntityRespVO();

        AttrEntity attrEntity = this.getById(attrId);

        BeanUtils.copyProperties(attrEntity, respVO);

        //1,设置分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationdao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                respVO.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    respVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }
        }


        //catelogPath
        CategoryEntity byId = categoryService.getById(attrEntity.getCatelogId());
        if (byId != null) {

            Long[] categoryPath = categoryService.findCategoryPath(byId.getCatId());

            respVO.setCatelogName(byId.getName());
            respVO.setCatelogPath(categoryPath);

        }

        return respVO;
    }


    @Transactional
    @Override
    public void updateAttr(AttrEntityVO attr) {

        AttrEntity attrEntity = new AttrEntity();

        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            //修改分组关联
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            Integer count = attrAttrgroupRelationdao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {

                attrAttrgroupRelationdao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));

            } else {

                attrAttrgroupRelationdao.insert(relationEntity);

            }
        }
    }

    @Transactional
    @Override
    public List<AttrEntity> QueryAttrGroupRelation(Long attrgroupId) {


        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationdao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));


        List<Long> attrIds = entities.stream().map((entity) -> {


            return entity.getAttrId();


        }).collect(Collectors.toList());

        if (attrIds.size() == 0 || attrIds == null) {

            return null;

        }

        List<AttrEntity> attrEntities = this.listByIds(attrIds);

        return attrEntities;

    }

    @Transactional
    @Override
    public void DeleteAttrGroupRelation(AttrGroupDeleteVo[] attrgroupId) {

        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = Arrays.asList(attrgroupId).stream().map((item) -> {

            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);

            return relationEntity;

        }).collect(Collectors.toList());

        attrAttrgroupRelationdao.DeleteBatch(attrAttrgroupRelationEntities);

    }

    @Transactional
    @Override
    public PageUtils queryNoAttrPage(Map<String, Object> params, Long attrGroupId) {

        //1，当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroup = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroup.getCatelogId();

        //2，当前分组只能关联别的分组没有引用的属性
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));

        List<Long> groupIds = group.stream().map((item) -> {

            return item.getAttrGroupId();
        }).collect(Collectors.toList());


        //2.1）、当前分类下的其他分组
        List<AttrAttrgroupRelationEntity> attr_groups = attrAttrgroupRelationdao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        //2.2）、这些分组关联的属性
        List<Long> attrIds = attr_groups.stream().map((item) -> {

            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3）、从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrIds != null && attrIds.size() > 0){
            wrapper.notIn("attr_id",attrIds );
        }

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.eq("attr_id",key).or().like("attr_name",key);
        }


        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);


        return new PageUtils(page);
    }

    @Override
    public List<Long> getAbleCheckAttrs(List<Long> ids) {
        return baseMapper.getAbleCheckAttrs(ids);
    }


}